#include "common.h"

// 初始化消息队列
void msg_queue_init(MsgQueue* queue)
{
    queue->head=NULL;
    queue->tail=NULL;
    queue->running=1;
    pthread_mutex_init(&queue->mutex,NULL);
    pthread_cond_init(&queue->cond,NULL);

}

// 向队列推送数据
void msg_queue_send(MsgQueue* queue,const char* json_buf)
{
    if(!queue||!json_buf)
    {
        return;
    }

    // 创建新节点
    MsgNode *node=(MsgNode*)malloc(sizeof(MsgNode));
    node->json_buf=strdup(json_buf);
    node->next=NULL;

    //加锁操作队列
    pthread_mutex_lock(&queue->mutex);
    if(!queue->head)
    {
        queue->head=queue->tail=node;
    }
    else
    {
        queue->tail->next=node;
        queue->tail=node;
    }
    pthread_cond_signal(&queue->cond); //通知用户有新数据
    pthread_mutex_unlock(&queue->mutex);

}

//从队列中取出数据
char *msg_queue_read(MsgQueue* queue)
{
    if(!queue)
    {
        return NULL;
    }

    pthread_mutex_lock(&queue->mutex);
    //阻塞等待:队列空闲且运行
    while(queue->running&&!queue->head)
    {
        pthread_cond_wait(&queue->cond,&queue->mutex);
    }

    //队列退出
    if(!queue->running)
    {
        pthread_mutex_unlock(&queue->mutex);
        return NULL;
    }

    //取出队头节点
    MsgNode* node=queue->head;
    char* json_buf=node->json_buf; //保存json字符串
    queue->head=queue->head->next;
    if(!queue->head)
    {
        queue->tail=NULL; // 队列空时尾指针置空
    }
    free(node); // 释放节点
    pthread_mutex_unlock(&queue->mutex);
    return json_buf;
 
}

//销毁消息队列
void msg_queue_destory(MsgQueue* queue)
{
    if(!queue)
    {
        return;
    }
    pthread_mutex_lock(&queue->mutex);
    queue->running=0; //停止运行
    pthread_cond_broadcast(&queue->cond); //唤醒阻塞的用户
    pthread_mutex_unlock(&queue->mutex);

    //释放剩余节点
    MsgNode* curr=queue->head;
    while(curr)
    {
        MsgNode* next=curr->next;
        free(curr->json_buf);
        free(curr);
        curr=next;
    }

    //销毁锁和条件变量
    pthread_mutex_destroy(&queue->mutex);
    pthread_cond_destroy(&queue->cond);
}

